<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="600" :fullscreen="false">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item :label="t('stageMajorGroup.fields.id')">
        <div>{{ formData.majorType }}</div>
      </el-form-item>
      <!-- 仅博士 -->
      <template v-if="instanceRule?.amountType === 1">
        <el-form-item :label="t('stageMajorGroup.fields.phdAmount')" prop="phdAmount">
          <el-input-number
            v-model="formData.phdAmount"
            :placeholder="t('common.inputTextPlaceholder') + t('stageMajorGroup.fields.phdAmount')"
            :min="0"
            class="better-number-input !w-1/1"
            controls-position="right"
          />
        </el-form-item>
      </template>
      <!-- 仅硕士 -->
      <template v-if="instanceRule?.amountType === 2">
        <el-form-item :label="t('stageMajorGroup.fields.masterAmount')" prop="masterAmount">
          <el-input-number
            v-model="formData.masterAmount"
            :placeholder="
              t('common.inputTextPlaceholder') + t('stageMajorGroup.fields.masterAmount')
            "
            :min="0"
            class="better-number-input !w-1/1"
            controls-position="right"
          />
        </el-form-item>
      </template>
      <!-- 博士硕士并列 -->
      <template v-if="instanceRule?.amountType === 3">
        <el-form-item :label="t('stageMajorGroup.fields.phdAmount')" prop="phdAmount">
          <el-input-number
            v-model="formData.phdAmount"
            :placeholder="t('common.inputTextPlaceholder') + t('stageMajorGroup.fields.phdAmount')"
            :min="0"
            class="better-number-input !w-1/1"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item :label="t('stageMajorGroup.fields.masterAmount')" prop="masterAmount">
          <el-input-number
            v-model="formData.masterAmount"
            :placeholder="
              t('common.inputTextPlaceholder') + t('stageMajorGroup.fields.masterAmount')
            "
            :min="0"
            class="better-number-input !w-1/1"
            controls-position="right"
          />
        </el-form-item>
      </template>
      <!-- 博士硕士合并 -->
      <template v-if="instanceRule?.amountType === 4">
        <el-form-item :label="t('stageMajorGroup.fields.totalAmount')" prop="totalAmount">
          <el-input-number
            v-model="formData.totalAmount"
            :placeholder="
              t('common.inputTextPlaceholder') + t('stageMajorGroup.fields.totalAmount')
            "
            :min="0"
            class="better-number-input !w-1/1"
            controls-position="right"
          />
        </el-form-item>
      </template>
      <el-link type="primary" @click="handleShowJudge" :disabled="!formData.id">
        {{ t('judgeScene.card.viewJudge') }}
      </el-link>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading"
        >{{ t('common.ok') }}
      </el-button>
      <el-button @click="dialogVisible = false">{{ t('common.cancel') }}</el-button>
    </template>
  </Dialog>

  <!-- 查看评委 -->
  <StageJudgeSelect ref="stageJudgeSelectRef" />
</template>
<script setup lang="ts">
import { StageMajorGroupApi, StageMajorGroupVO } from '@/api/awards/stagemajorgroup'
import { FormRules } from 'element-plus'
import { InstanceRuleVO } from '@/api/awards/instancerule'
import StageJudgeSelect from '@/views/awards/stagejudge/components/StageJudgeSelect.vue'

/** 阶段-专业分组设置 表单 */
defineOptions({ name: 'StageMajorGroupForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  awardsId: undefined,
  instanceRuleId: undefined,
  majorType: undefined,
  phdAmount: undefined,
  masterAmount: undefined,
  totalAmount: undefined,
  remark: undefined
})
const formRules = reactive<FormRules>({
  phdAmount: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('stageMajorGroup.fields.phdAmount'),
      trigger: 'blur'
    }
  ],
  masterAmount: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('stageMajorGroup.fields.masterAmount'),
      trigger: 'blur'
    }
  ],
  totalAmount: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('stageMajorGroup.fields.totalAmount'),
      trigger: 'blur'
    }
  ]
})
const formRef = ref() // 表单 Ref

const instanceRule = ref<InstanceRuleVO>()
const majorGroup = ref<StageMajorGroupVO>()

/** 打开弹窗 */
const open = async (rule: InstanceRuleVO, type: string, major?: StageMajorGroupVO) => {
  instanceRule.value = rule
  majorGroup.value = major
  dialogVisible.value = true
  if (major?.id) {
    dialogTitle.value = t('action.update')
    formType.value = 'update'
  } else {
    dialogTitle.value = t('action.create')
    formType.value = 'create'
  }
  resetForm()
  // 修改时，设置数据
  if (major?.id) {
    formLoading.value = true
    try {
      formData.value = await StageMajorGroupApi.getStageMajorGroup(major.id)
    } finally {
      formLoading.value = false
    }
  }
  formData.value.awardsId = rule.awardsId as any
  formData.value.instanceRuleId = rule.id as any
  formData.value.majorType = type as any
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  try {
    await formRef.value.validate()
  } catch {
    return
  }
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as StageMajorGroupVO
    if (formType.value === 'create') {
      await StageMajorGroupApi.createStageMajorGroup(data)
      message.success(t('common.createSuccess'))
    } else {
      await StageMajorGroupApi.updateStageMajorGroup(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    awardsId: undefined,
    instanceRuleId: undefined,
    majorType: undefined,
    phdAmount: undefined,
    masterAmount: undefined,
    totalAmount: undefined,
    remark: undefined
  }
  formRef.value?.resetFields()
}

// 查看评委
const stageJudgeSelectRef = ref<InstanceType<typeof StageJudgeSelect>>()
const handleShowJudge = () => {
  if (instanceRule.value && majorGroup.value) {
    stageJudgeSelectRef.value?.open(
      instanceRule.value.awardsId,
      majorGroup.value.id,
      instanceRule.value.id
    )
  }
}
</script>
